/**
 * Copyright (C) 2008 GeoScheduler Team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */

package org.geoscheduler.exceptions;

import org.geoscheduler.Context;
import org.geoscheduler.commons.msgs.BasicMessageSeverities;
import org.geoscheduler.commons.msgs.Message;
import org.geoscheduler.commons.msgs.ParametrizedMessage;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONWrappedException extends RuntimeException {

	private static final long serialVersionUID = 4653922792583452819L;
	private final Message message;

	public JSONWrappedException(Enum<?> message, Object... params) {
		this(message, null, params);
	}

	public JSONWrappedException(Enum<?> message, Throwable cause, Object... params) {
		super(message.name(), cause);
		this.message = new ParametrizedMessage(message, BasicMessageSeverities.ERROR, asStringArray(params));
	}

	private String[] asStringArray(Object[] array) {
		String[] strArray = new String[array.length];
		for (int i = 0; i < array.length; i++) {
			strArray[i] = String.valueOf(array[i]);
		}
		return strArray;
	}

	public JSONWrappedException(Message message) {
		super(message.getMessage());
		this.message = message;
	}

	public Message getInnerMessage() {
		return this.message;
	}

	public JSONObject getMessage(Context ctx) {
		try {
			return ctx.getMsgMarshaller().marshall(message, ctx.getLocale());
		} catch (JSONException ex) {
			throw new IllegalStateException("failed to generate JSON result object for " + this);
		}
	}
}
